package ru.belokuriha_online.resort_hotels_belokuriha;

import java.io.File;
import java.io.FileInputStream;

import java.io.InputStream;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.res.Configuration;

import android.util.DisplayMetrics;
import android.util.FloatMath;
import android.graphics.drawable.Drawable;
import android.graphics.Matrix;
import android.graphics.PointF;
import android.graphics.Rect;


import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.MotionEvent;

import android.widget.ImageView;

import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;





public class Picsanator extends Activity implements OnTouchListener {


	String spprisepath;
	String fileaboutPath;
	
	ImageView picimgsan;
	
	//private static float MIN_ZOOM = 1f;
	//private static float MAX_ZOOM = 5f;
	public float MIN_ZOOM;
	public float MAX_ZOOM;
	float kMIN_ZOOM;
	float k2MIN_ZOOM;
	Matrix matrix;
	Matrix savedMatrix;
	
    static final int NONE = 0;
    static final int DRAG = 1;
    static final int ZOOM = 2;
    int mode = NONE;
    
    PointF start = new PointF();
    PointF mid = new PointF();
    float oldDist = 1f;
    Drawable disan;
    
    Integer tr;
    
   float scaleWidth;
   float scaleHeight;
   
	Bitmap bmp;
	public float scale;
	double scalexy;
	int bmpWidth;
	int bmpHeight;
	int tbmpWidth;
	int tbmpHeight;
	Bitmap resizeBmp;
	RelativeLayout lt1;
	
	DisplayMetrics dm;
	public float xl;
	public float yl;
	//
	int _y_up;
	int FlagOnlain;
	int sizelayw;
    int sizelayh;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) 
	{

		super.onCreate(savedInstanceState);
		setContentView(R.layout.picsanator);
		try {
		tr = 0;
		spprisepath = getIntent().getExtras().getString("spprisepath");
		fileaboutPath = getIntent().getExtras().getString("fileaboutPath");
		FlagOnlain = getIntent().getExtras().getInt("FlagOnlain");
		dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);
		matrix = new Matrix();
		savedMatrix = new Matrix();
		scale = MIN_ZOOM;
		 
			
		try {
		File aboutpic = new File(fileaboutPath);
		InputStream isan = new FileInputStream(aboutpic);

		
		bmp = BitmapFactory.decodeStream(isan);
		lt1 = (RelativeLayout) findViewById(R.id.Lt1);
		
		picimgsan = (ImageView) findViewById(R.id.picimageSan);	
		  
		
		bmpWidth = bmp.getWidth();
		bmpHeight = bmp.getHeight();
		
		
		resizeBmp = Bitmap.createBitmap(bmp,0,0,bmpWidth,bmpHeight, matrix, true);
		
		isan.close();
		picimgsan.setImageBitmap(resizeBmp);
		Handler handler = new Handler();
		handler.postDelayed(new Runnable() {
		 
		    @Override
		    public void run() {
		       
		        sizelayw = picimgsan.getWidth();
		        sizelayh = picimgsan.getHeight();
		        xl = sizelayw/2;
				yl = sizelayh/2;
				
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
					if (sizelayw >= bmpWidth) {
						// MIN_ZOOM = 1f*sizelayh/bmpHeight;
						MIN_ZOOM = 1f*sizelayw/bmpWidth;
						 
						 }	
						 if (sizelayw < bmpWidth) {
							// MIN_ZOOM = 1f*sizelayh/bmpHeight;
							 MIN_ZOOM = 1f*sizelayw/bmpWidth; 
							
						 }
				}
				if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
					if (sizelayw >= bmpWidth) {
						//MIN_ZOOM = 1f*sizelayw/bmpWidth;
						 MIN_ZOOM = 1f*sizelayh/bmpHeight;
						 
						 }	
						 if (sizelayw < bmpWidth) {
							 //MIN_ZOOM = 1f*sizelayw/bmpWidth;
							 MIN_ZOOM = 1f*sizelayh/bmpHeight;
							
						 }
				}
		
				 scale = MIN_ZOOM;
				 MAX_ZOOM = MIN_ZOOM*5f;
				 picimgsan.setScaleType(ImageView.ScaleType.MATRIX);
				 matrix.postTranslate((sizelayw-bmpWidth)/2, (sizelayh -bmpHeight)/2);
				
				picimgsan.setImageMatrix(matrix);		
				matrix.postScale(scale, scale,xl,yl);
		       
				savedMatrix.set(matrix);
				picimgsan.setImageMatrix(matrix);
		    }
		},100);
		
		
		//
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		try {		
		picimgsan.setOnTouchListener(this);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
			
		
		
		
		final TextView picexit =(TextView) findViewById(R.id.textViewClosepicsan);
		picexit.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Picsanator.super.onDestroy();
				finish();
				Picsanator.super.onDestroy();
			}	
		});
	} catch (Exception e) {
		// TODO: handle exception
	}
		
	}
	
	
	public boolean onTouch(View v, MotionEvent event) 
    {
        ImageView view = (ImageView) v;
        
       float tscale;

        switch (event.getAction() & MotionEvent.ACTION_MASK) 
        {
            case MotionEvent.ACTION_DOWN:  
                                                savedMatrix.set(matrix);
                                                start.set(event.getX(), event.getY());
                                                mode = DRAG;
                                               
                                                break;

            case MotionEvent.ACTION_UP: 
										break;
            case MotionEvent.ACTION_CANCEL: 
            								break;

            case MotionEvent.ACTION_POINTER_UP: 
                                                mode = NONE;
                                                break;

            case MotionEvent.ACTION_POINTER_DOWN: 

                                                oldDist = spacing(event);
                                                if (oldDist > 5f) {
                                                    savedMatrix.set(matrix);
                                                    midPoint(mid, event);
                                                    mode = ZOOM;
                                                   
                                                }
                                                break;

            case MotionEvent.ACTION_MOVE:
            									
                                                if (mode == DRAG) 
                                                { 
                                                    matrix.set(savedMatrix);
                                                    savedMatrix.set(matrix);
                                                    matrix.postTranslate(event.getX() - start.x, event.getY() - start.y); 
                                                    xl = event.getX();
                                                    yl = event.getY();
                                                      
                                                	
                                                } 
                                                else if (mode == ZOOM) 
                                                { 
                                                	
                                                    float newDist = spacing(event);
                                                    if (newDist > 5f) 
                                                    {    
                                                    	
                                                        matrix.set(savedMatrix);
                                                        savedMatrix.set(matrix);
                                                      
                                                        tscale = (newDist / oldDist);
                                                        
	                                                        xl = mid.x;
	                                                        yl = mid.y;	                                                        
	                                                        matrix.postScale(tscale, tscale, xl, yl);
                                                       
                                                          
                                                    }
                                                }
                                                break;
        }
       
       
       
        limitDrag(matrix, view);
        limitZoom(matrix);
        view.setImageMatrix(matrix); 
       
        return true; 
    }



    
	private float spacing(MotionEvent event) 
    {
        float x = event.getX(0) - event.getX(1);
        float y = event.getY(0) - event.getY(1);
        return FloatMath.sqrt(x * x + y * y);
    }



    private void midPoint(PointF point, MotionEvent event) 
    {
        float x = event.getX(0) + event.getX(1);
        float y = event.getY(0) + event.getY(1);
        point.set(x / 2, y / 2);
    }
    
    private void limitZoom(Matrix mt) {
        float[] values = new float[9];
        mt.getValues(values);
      
       float scaleX = values[Matrix.MSCALE_X];
       float scaleY = values[Matrix.MSCALE_Y];
        
        if(scaleX > MAX_ZOOM) {
            scaleX = MAX_ZOOM;
        } else if(scaleX < MIN_ZOOM) {
            scaleX = MIN_ZOOM;
        }

        if(scaleY > MAX_ZOOM) {
            scaleY = MAX_ZOOM;
        } else if(scaleY < MIN_ZOOM) {
            scaleY = MIN_ZOOM;
        }
       
        values[Matrix.MSCALE_X] = scaleX;
        values[Matrix.MSCALE_Y] = scaleY; 
        mt.setValues(values);
    }
    private void limitDrag(Matrix tm, ImageView tview) {
    	
        float[] values = new float[9];
        tm.getValues(values);
        float transX = values[Matrix.MTRANS_X];
        float transY = values[Matrix.MTRANS_Y];
       
        float scaleX = values[Matrix.MSCALE_X];
        float scaleY = values[Matrix.MSCALE_Y];
        
        Rect bounds = tview.getDrawable().getBounds();
        int viewWidth = lt1.getWidth();
        int viewHeight = lt1.getHeight();
       
        float width = (bounds.right - bounds.left)* scaleX;
        float height = (bounds.bottom - bounds.top)* scaleY;
      
        float minX = 0; 
        float minY = 0;
        
        if (viewWidth >= width) {
	        if(transX > (viewWidth - width)) {
	            transX = viewWidth - width;
	        } else if(transX < minX) {
	            transX = minX;
	        }
        }
        if (viewWidth < width) {
	        if(transX < (-width + viewWidth)) {
	            transX = -width + viewWidth;
	        } else if(transX > minX) {
	            transX = minX;
	        }
        } 
        if (viewHeight >= height) { 
	        if(transY > (viewHeight - height)) {
	            transY = viewHeight - height;
	        } else if(transY < minY) {
	            transY = minY;
	        }
        }
        if (viewHeight < height) { 
	        if(transY < (-height + viewHeight)) {
	            transY = -height + viewHeight;
	        } else if(transY > minY) {
	            transY = minY;
	        }
        }
       
        values[Matrix.MTRANS_X] = transX;
        values[Matrix.MTRANS_Y] = transY; 
        values[Matrix.MSCALE_X] = scaleX;
        values[Matrix.MSCALE_Y] = scaleY; 
        tm.setValues(values);

    	
    }
    
	/////*
	
	public boolean onCreateOptionsMenu(Menu menu) { 

		getMenuInflater().inflate(R.menu.pmenu, menu);

		return true;
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) { 
		if (FlagOnlain == 0) {
			menu.findItem(R.id.loaditem1).setVisible(true);
			menu.findItem(R.id.loaditem1).setEnabled(true);
			} else
			{			
			menu.findItem(R.id.loaditem1).setEnabled(false);
			menu.findItem(R.id.loaditem1).setVisible(false);
			}
			menu.findItem(R.id.pitem2).setEnabled(true);
			menu.findItem(R.id.abitem3).setEnabled(true);
		return super.onPrepareOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) { 

		case R.id.loaditem1: 
			GoMain();
			break; 


		case R.id.pitem2:
			//
			setResult(9);
			finish();

			break; 
		case R.id.abitem3: 
			//
			setResult(5);
			finish();

			break;
		}       


		return super.onOptionsItemSelected(item); 

	} 
	private void GoMain() {
		AlertDialog.Builder buildergomain = new AlertDialog.Builder(this);
		buildergomain.setTitle(R.string.lt_app);		
		buildergomain.setMessage(R.string.lmmm_app);		
		buildergomain.setNegativeButton(R.string.qn_app, null);
		buildergomain.setPositiveButton(R.string.qy_app, new OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				setResult(7);
				finish(); 	            	

			}
		}).create().show();	
	}
	@Override 
	protected void onDestroy() {
		super.onDestroy();
		
		try {
		if(resizeBmp != null) {
			resizeBmp.recycle();
			resizeBmp = null;
		}
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		System.gc();
		
	}
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == 7) {
			setResult(7);
			finish();
		}

		if (resultCode ==  5) {
			try {
				openOptionsMenu();
			} catch (Exception e) {

			}
		}

	}






}
